package cn.tedu._04weibo.controller;

import cn.tedu._04weibo.base.response.JsonResult;
import cn.tedu._04weibo.base.response.StatusCode;
import cn.tedu._04weibo.mapper.UserMapper;
import cn.tedu._04weibo.pojo.dto.UserLoginParam;
import cn.tedu._04weibo.pojo.dto.UserRegParam;
import cn.tedu._04weibo.pojo.entity.User;
import cn.tedu._04weibo.pojo.vo.UserVO;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("reg")
    @Operation(summary = "注册功能")
    public JsonResult userRegister(@RequestBody @Validated UserRegParam userRegParam){
        log.debug("开始处理【用户注册】的请求，参数：{}", userRegParam);
        userMapper.userInsert(userRegParam);
        return JsonResult.ok(userRegParam);
    }
    @Operation(summary = "用户登录功能")
    @PostMapping("login")
    public JsonResult userLogin(@RequestBody  UserLoginParam userLoginParam,HttpSession session){
        log.debug("开始处理【用户登录】的请求，参数：{}", userLoginParam);
        UserVO userVO=userMapper.login(userLoginParam);
        if (userVO == null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        session.setAttribute("user",userVO);
        return JsonResult.ok(userVO);
    }

    @Operation(summary = "获取当前用户功能")
    @GetMapping("currentUser")
    public JsonResult getCurrentUser(HttpSession session){
        log.debug("开始处理【获取当前用户】的请求");
        UserVO userVO = (UserVO) session.getAttribute("user");
        User user = userMapper.selectUser(userVO.getUsername());
        return JsonResult.ok(user);
    }

}
